const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: ({ z_data: JSON.stringify(data) }),
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res);
        if (res.statusCode == 200) {
          
          resolve(res.data);
          
        } else {
          reject(res.errMsg);
        }
      },
      fail: function (err) {
        reject(err)
       
      }
    })
  });
};

//多张图片上传
function uploadimg(data, chenggongfangfa) {
  var that = this,
    i = data.i ? data.i : 0,//当前上传的哪张图片
    success = data.success ? data.success : 0,//上传成功的个数
    fail = data.fail ? data.fail : 0;//上传失败的个数
  wx.uploadFile({
    url: data.url,
    filePath: data.path[i],
    name: 'file',//这里根据自己的实际情况改
    formData: null,//这里是上传图片时一起上传的数据
    success: (resp) => {

      if (resp.statusCode == 200) {

        success++;//图片上传成功，图片上传成功的变量+1
        var zhuanhuandata = JSON.parse(resp.data);
        data.pic.push(zhuanhuandata.WS_RET_DATA.IMG_PATH);
        console.log(resp);
        console.log(i);

      } 
     
      //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
    },
    fail: (res) => {
      fail++;//图片上传失败，图片上传失败的变量+1
      console.log('fail:' + i + "fail:" + fail);
    },
    complete: (res) => {
      console.log(res.data.src);
      i++;//这个图片执行完上传后，开始上传下一张
      if (i == data.path.length) {   //当图片传完时，停止调用          
        console.log('执行完毕');
        console.log(data.pic);
        console.log('成功：' + success + " 失败：" + fail);

        chenggongfangfa(data.pic);

      } else {//若图片还没有传完，则继续调用函数
        console.log(i);
        data.i = i;
        data.success = success;
        data.fail = fail;
        that.uploadimg(data, chenggongfangfa);
      }

    }
  });
};

module.exports = {
  formatTime: formatTime,
  request: request,
  uploadimg: uploadimg,
}
